package com.demo.doc_pdf_demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.doc_pdf_demo.util.Doc2pdfLibreofficeUtil;
import com.demo.doc_pdf_demo.util.MultipartFileToFile;
import com.demo.doc_pdf_demo.util.Word2PdfUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 测试类
 * @Author: L.Wen
 * @Date: 2021/6/16 17:20
 */
@RestController
@RequestMapping("test")
public class TestController {

    @Value("${word2Pdf.source-path}")
    private String sourcePath;

    @Value("${word2Pdf.dest-path}")
    private String destPath;

    @Value("${word2Pdf.convert-url}")
    private String convertUrl;
    /**
     * 允许的文件类型
     */
    private static final List<String> ALLOW_TYPES = Arrays.asList("doc", "docx");

    @RequestMapping("testConvert")
    public JSONObject testConvert(@RequestParam("docxPath") String docxPath) {
        try {
            return Doc2pdfLibreofficeUtil.doc2pdf(docxPath);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("testWord2PdfUtil")
    public String testWord2PdfUtil() {
        String wordFile = "D:\\tmpfile\\work\\123456.doc";
        String pdfFile = "D:\\tmpfile\\work\\123456-.pdf";
        Word2PdfUtil.wordToPDF(wordFile, pdfFile);
        return pdfFile;
    }

    @PostMapping("word2PdfPath")
    public JSONObject word2PdfPath(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = checkFile(multipartFile);
        if (result != null) {
            return result;
        }
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println(multipartFile.getContentType());
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String wordFile = sourcePath + System.currentTimeMillis() + originalFilename;
        String pdfFile = destPath + fileName + ".pdf";
        String filePath = MultipartFileToFile.mult2File(wordFile, multipartFile);
        Word2PdfUtil.wordToPDF(filePath, pdfFile);
        result = new JSONObject();
        result.put("code", 2000);
        result.put("data", pdfFile);
        return result;
    }

    /**
     * 返回文件二进制数组
     *
     * @param multipartFile
     * @param request
     * @param response
     * @return
     */
    @PostMapping("word2PdfByteArray")
    public JSONObject word2PdfByteArray(MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = checkFile(multipartFile);
        if (result != null) {
            return result;
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String wordFile = sourcePath + originalFilename;
        String pdfFile = destPath + fileName + ".pdf";
        String filePath = MultipartFileToFile.mult2File(wordFile, multipartFile);
        Word2PdfUtil.wordToPDF(filePath, pdfFile);
        try {
            // 创建file对象
            File file = new File(pdfFile);
            FileInputStream fileInputStream = new FileInputStream(file);
            result = new JSONObject();
            result.put("code", 2000);
            result.put("body", IOUtils.toByteArray(fileInputStream));
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result = new JSONObject();
            result.put("code", 5000);
            result.put("message", "系统错误！");
            return result;
        }
    }

    /**
     * 返回流
     *
     * @param multipartFile
     * @param request
     * @param response
     */
    @PostMapping("word2PdfStream")
    public ResponseEntity<Resource> word2PdfStream(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = checkFile(multipartFile);
        if (result != null) {
            return null;
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String wordFile = sourcePath + originalFilename;
        String pdfFile = destPath + fileName + ".pdf";
        String filePath = MultipartFileToFile.mult2File(wordFile, multipartFile);
        Word2PdfUtil.wordToPDF(filePath, pdfFile);
        // 创建file对象
        File fileNew = new File(pdfFile);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + fileNew.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        return ResponseEntity.ok().headers(headers).contentLength(fileNew.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(fileNew));
    }

    private JSONObject checkFile(MultipartFile multipartFile) {
        JSONObject result = new JSONObject();
        if (multipartFile == null) {
            result.put("code", 4000);
            result.put("message", "文件为空！");
            return result;
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename == null) {
            result.put("code", 4000);
            result.put("message", "文件名为空！");
            return result;
        }
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (!ALLOW_TYPES.contains(ext)) {
            result.put("code", 4000);
            result.put("message", "文件类型不支持！");
            return result;
        }
        return null;
    }

}
